import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { log } from 'console';
declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-conch-log',
	templateUrl: './conch-log.component.html',
	styleUrls: ['./conch-log.component.css']
})
export class ConchLogComponent implements OnInit {
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	deviceId: string = '';//设备ID
	carNumber: string = ''; //车牌号码
	startTime: string = ''; //开始时间
	endTime: string = ''; //结束时间
	haiLuoDeviceNo: string = ''; // 海螺设备号
	selectedCompanyId: string = '';
	selectedCompanyName: string = '';
	activeSelected: string = '';
	pushState: string = '';
	pushMethodType: string = '';
	allChecked: boolean = false; // 全选状态
	selected: any[] = []; // 选中的数据
	selectedRow: any;
	searchKey: string = ''; //搜索keyword

	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute,) {
		activatedRoute.queryParams.subscribe(queryParams => {

		});
	}

	// 接收子组件传递过来的数据
	getSelectTableTime(time) {
		this.startTime = time.startTime
		this.endTime = time.endTime
		this.load()
	}

	//公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
	ngOnInit() {
		this.initBtn();
		this.load()
	}

	isShowPush: boolean = false; // 全选状态
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_loginfo:conchLog')));
		if (!btnData) {
			return
		};
		for (let item of btnData) {
			if (item.sourceKey === "loginfo:conchLog:pushBtn" && item.parentId) {
				this.isShowPush = true;
			}
		}
	}
	//  初始化加载list数据
	load() {

		this.allChecked = false; // 全选置空
		this.selected = []
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				startTime: this.startTime,
				endTime: this.endTime,
				haiLuoDeviceNo: this.haiLuoDeviceNo,
				pushState: this.pushState == '' ? null : this.pushState,
				pushMethodType: this.pushMethodType == '' ? null : this.pushMethodType,
				deviceId: this.deviceId,
				companyId: this.selectedCompanyId,
				companyName: this.selectedCompanyName,
				carNumber: this.carNumber,
				searchKey: this.searchKey
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("haiLuoPushCarLog/queryHaiLuoPushCarLogPage.html", reqdata).subscribe(data => {
			if (!data.isSuccess) {
				this.jsonApiService.message(data.message);
				return;
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	ngOnDestroy() {
		document.onclick = null;
	}
	//刷新
	refresh() {
		this.load();
	}
	//查询
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	// 批量推送
	pushAll() {
		if (this.selected.length) {
			let reqdata = 'ids=' + this.selected.join(',');
			this.jsonApiService.http("haiLuoPushCarLog/pushRestartByIds.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) { this.load(); }
			})
		} else {
			this.jsonApiService.message('请勾选数据推送');
		}
	}
	//单独推送
	pushItem(row) {
		let selected = this.selected.length ? this.selected : [row.id]
		let reqdata = 'id=' + selected;
		this.jsonApiService.http("haiLuoPushCarLog/pushRestart.html", reqdata).subscribe(result => {
			this.jsonApiService.message(result.message);
			if (result.success) { this.load(); }
		});
	}
	//table复选框数据row选中事件回调:处理选中状态和deviceId
	rowSelected(row, e, index) {
		var index = $.inArray(row.id, this.selected);
		if (index === -1) {
			row.isChecked = true;
			this.selected.push(row.id);
		} else {
			row.isChecked = false;
			this.selected.splice(index, 1);
		}
		this.selected.length === this.pageSize ? this.allChecked = true : this.allChecked = false; //判断是否全选状态
	}
	//table 全部选中
	allSelected() {
		this.allChecked = !this.allChecked;
		if (!this.allChecked) {
			for (let item of this.tableData) {
				item['isChecked'] = false;
			}
			this.selected = [];
		} else {
			for (let item of this.tableData) {
				item['isChecked'] = true;
				this.selected.push(item.id);
			}
		}
	}

	/**
	 * 手动推送
	 */
	pushData: any = [
		{
			url: 'haiLuoPushCarLog/pushCarData.html',
			name: '推送车辆轨迹',
			dataList: [{
				name: '设备编号',
				key: 'deviceId',
				type: 'text',
				value: ''
			},
			{
				name: '开始日期',
				key: 'startTime',
				type: 'date',
				value: ''
			},
			{
				name: '结束日期',
				key: 'endTime',
				type: 'date',
				value: ''
			}]
		},
		{
			url: 'haiLuoPushCarLog/pushCarWeightData.html',
			name: '推送车辆载重+轨迹',
			dataList: [{
				name: '设备编号',
				key: 'deviceId',
				type: 'text',
				value: ''
			},
			{
				name: '开始日期',
				key: 'startTime',
				type: 'date',
				value: ''
			},
			{
				name: '结束日期',
				key: 'endTime',
				type: 'date',
				value: ''
			}]
		},
		{
			url: 'haiLuoPushCarLog/updateHaiLuoCarNumber.html',
			name: '修改车牌号',
			dataList: [{
				name: '设备编号',
				key: 'deviceId',
				type: 'text',
				value: ''
			},
			{
				name: '车牌号码',
				key: 'newCarNumber',
				type: 'text',
				value: ''
			}]
		},
		{
			url: 'haiLuoPushCarLog/settingServiceEndTime.html',
			name: '修改服务到期时间',
			dataList: [{
				name: '设备编号',
				key: 'deviceId',
				type: 'text',
				value: ''
			},
			{
				name: '设备结束时间',
				key: 'serviceEndTime',
				type: 'date',
				value: ''
			}]
		},
		{
			url: 'haiLuoPushCarLog/updateImei.html',
			name: '修改imei',
			dataList: [{
				name: '设备编号',
				type: 'text',
				key: 'deviceId',
				value: ''
			},
			{
				name: '海螺设备号',
				key: 'haiLuoDeviceId',
				type: 'text',
				value: ''
			}]
		}
	]

	// 倍数模式
	multiplePattern = {
		isChecked: false,
		wbWeight:'', // 磅单重量
		wbDate:'' // 出厂时间/重磅时间
	}

	//初始化日期插件
	initDate() {
		// common.initDatePicker('#serviceEndTime', 0)
		const that = this;
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			()=>{System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
				that.pushData.forEach((element,i) => {
					element.dataList.forEach(item => {
						if(item.type === 'date') {
							common.initDatePicker(`#${i + item.key}`, 0)
							$(`#${i + item.key}`).datetimepicker().on("changeDate", function (e) {
								item.value = common.dateToFormat(e.date)
							})
						}
					})
				});
				common.initDatePicker('#wbDate', 0)
				$('#wbDate').datetimepicker().on("changeDate", function (e) {
					that.multiplePattern.wbDate = common.dateToFormat(e.date)
				})
			})
		})
	}

	manualPush(modal) {
		let list = JSON.parse(JSON.stringify(this.pushData))
		list.forEach((element,i) => {
			element.dataList.forEach(item => {
				item.value = ''
			})
		});
		this.pushData = JSON.parse(JSON.stringify(list))
		this.multiplePattern =  {
			isChecked: false,
			wbWeight:'',
			wbDate:''
		}
	  	modal.show()

		setTimeout(() => {
			this.initDate()
		})
	}
	closePushModal(modal) {
		modal.hide()
	}
	submitPush(index) {
		let list = JSON.parse(JSON.stringify(this.pushData))
		console.log(index)
		console.log(list[index])
		let returnValue = true

		list[index].dataList.forEach(element => {
			if (!element.value) {
				this.jsonApiService.message('请输入' + element.name);
				returnValue = false
				return
			}
			if (element.key == 'startTime' || element.key == 'endTime' || element.key == 'serviceEndTime') {
				if (!common.checkDateFormat(element.value)) {
					this.jsonApiService.message('请输入正确的日期格式');
					returnValue = false
				}
			}
		});

		if(index === 1 && this.multiplePattern.isChecked) {
			// if(!this.multiplePattern.wbWeight) {
			// 	this.jsonApiService.message('请输入磅单重量');
			// 	returnValue = false
			// }
			if(!this.multiplePattern.wbDate) {
				this.jsonApiService.message('请输入出厂时间');
				returnValue = false
			}
		}

		if (returnValue) {
			let reqdata = "";
			for (let i = 0; i < list[index].dataList.length; i++) {
				reqdata += "&" + list[index].dataList[i].key + "=" + list[index].dataList[i].value;
			}
			if(index === 1 && this.multiplePattern.isChecked){
				reqdata += "&wbWeight=" + this.multiplePattern.wbWeight
				reqdata += "&wbDate=" + this.multiplePattern.wbDate
			}
			reqdata = reqdata.replace("&", "")
			this.jsonApiService.http(list[index].url, reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) { this.load(); }
			})
		}

	}
}
